<template>
  <div :class="className" :style="{ height, width }" />
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: "TopBar",
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    tdata: {
      type: Array,
      required: true
    },
    xLabels: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    initChart() {
      const chartDom = this.$el;
      this.chart = echarts.init(chartDom);
      this.updateChart(this.tdata, this.xLabels); // 传递 xLabels
    },
    updateChart(data, xLabels) {
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: xLabels,
          axisLabel: {
            interval: 0, // 强制显示所有标签
            rotate: 45, // 旋转标签以避免重叠
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: data.map(item => item.value),
            type: 'bar',
            itemStyle: {
              color: params => {
                const item = data[params.dataIndex];
                return item.color || '#000';
              }
            }
          }
        ]
      });
    }
  },
  watch: {
    tdata: {
      handler(newData) {
        if (this.chart) {
          this.updateChart(newData, this.xLabels);
        }
      },
      deep: true // Watch for deep changes in the array
    },
    xLabels: {
      handler(newLabels) {
        if (this.chart) {
          this.updateChart(this.tdata, newLabels);
        }
      },
      deep: true // Watch for deep changes in the array
    }
  }
}
</script>

<style scoped lang="scss">
.chart {
  width: 100%;
  height: 300px; // 添加样式以确保组件显示
}
</style>
